<?php
/**
 * 获取指定日期所在周的第一天和最后一天
 * @param string $day
 * @return array
 */
function getDaysInWeek(string $day){
    $lastday=date('Y-m-d',strtotime("$day Sunday"));
    $firstday=date('Y-m-d',strtotime("$lastday -6 days"));
    return array($firstday,$lastday);
}

/**
 * 获取指定日期所在周的第一天和最后一天
 * @param string $day
 * @return array
 */
function getDaysInMonth(string $day){
    $firstday = date('Y-m-01',strtotime($day));
    $lastday = date('Y-m-d',strtotime("$firstday +1 month -1 day"));
    return array($firstday,$lastday);
}

function goExit($url, $msg=null) {
    if(!$url) $url = 'index.php';
    if(in_array($url, ['index.php','login.php','logout.php'])) {
        $top = true;
    } else $top = false;
    echo '<script type="text/javascript">';
    if($msg) {
        echo 'alert("'.$msg.'");';
    }
    if($top) echo 'window.top.location.href="'.$url.'";</script>';
    else echo 'location.href="'.$url.'";';
    echo '</script>';
    //header('Location:'.$url);
    exit;
}

function checkLogin() {
    global $_SESSION;
    if(!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_group'])) {
        goExit('login.php');
    }
}

function getFuncs($group_id) {
    if(!$group_id) return [];
    if(!$_SESSION['admin_id']) return [];
    global $DB;
    $select_group = $DB->get('admin_groups', '*', ['id' => $group_id]);
    if(!isset($select_group['funcs'])) return [];
    else {
        $user_extra = $DB->get('admin_user', ['funcs'], ['id'=>$_SESSION['admin_id']]);
        $user_extra = explode(',', $user_extra['funcs']);
        $funcs = explode(',', $select_group['funcs']);
        if(!empty($user_extra)) {
            foreach($user_extra as $ex) {
                if($ex > 0 && !in_array($ex, $funcs)) $funcs[] = $ex;
                if($ex < 0 && in_array(abs($ex), $funcs)) {
                    foreach($funcs as $k => $f) {
                        if(abs($ex) == $f) {
                            unset($funcs[$k]);
                            break;
                        }
                    }
                }
            }
        }
        if(count($funcs) < 1) return [];
        else return $funcs;
    }
}

function checkFunc($func_id, $msg=null) {
    $funcs = getFuncs($_SESSION['admin_group']);
    if(!in_array($func_id, $funcs)) {
        goExit('dashboard.php', $msg);
    }
}

function add_version_log($module,$action,$type,$data,$data_to = []){
    global $DB;
    $add_data = [
        'module' => $module,
        'action' => $action,
        'type'   => $type,
        'data'   => json_encode($data),
        'create_time' => time()
    ];
    if ($data_to){
        $add_data['data_to'] = json_encode($data_to);
    }
    $DB->insert('game_version_log',$add_data);
}
